import requests,logging


class Session():
    def __init__(self):
        '''
        创建一个session会话，这样就无须考虑cookies的问题
        '''
        self.without_token = requests.session()
        self.with_token = requests.session()
        token = self.get_token()
        self.with_token.headers['Authorization'] = 'JWT ' + token
        self.proxies = {'http':'http://127.0.0.1:8888'}

    def http_request(self,url,method,keys,data,is_token):
        '''
        定义请求方法
        :param url: 请求的url
        :param method: 请求的方法
        :param keys: 传参的关键字
        :param data: 传参的数据
        :param is_token: 请求是否需要携带token
        :return: Response
        '''
        # logging.info(f'url:{url},method:{method},keys:{keys},data:{data},is_token:{is_token}')
        if is_token:
            sess = self.with_token
        else:
            sess = self.without_token

        if method.upper() == 'GET':
            return sess.get(url,params=data,proxies=self.proxies)
        elif method.upper() == 'POST':
            if keys.lower() == 'data':
                return sess.post(url,data=data,proxies=self.proxies)
            else:
                return sess.post(url,json=data,proxies=self.proxies)
        elif method.upper() == 'PUT':
            return sess.put(url,data=data,proxies=self.proxies)
        elif method.upper() == 'PATCH':
            return sess.patch(url,data=data,proxies=self.proxies)
        elif method.upper() == 'DELETE':
            return sess.delete(url,proxies=self.proxies)
        else:
            raise TypeError(f'不支持{method}请求方法')

    def get_token(self):
        login_data = {
            'username':'admin',
            'password':'123456'
        }
        res = self.with_token.post('http://127.0.0.1:8000/login',data=login_data)
        return res.json()['token']

    def close(self):
        '''
        关闭session会话
        :return:
        '''
        self.without_token.close()
        self.with_token.close()

